from flask import Flask, request, render_template,send_from_directory,abort,redirect, url_for
import os
from onlyExcel import executeData

app = Flask(__name__)

UPLOAD_FOLDER = 'uploadDir'
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route('/')
def upload_form():
    return render_template('upload.html')

@app.route('/upload', methods=['POST'])
def upload_files():
    files = {}
    for file_key in ['commission_file', 'search_file']:
        file = request.files.get(file_key)
        if file:
            filename = file.filename
            file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            file.save(file_path)
            files[file_key] = file_path
        else:
            return f"File type not allowed or no file uploaded for {file_key}"
    
    # 处理勾选框
    platforms = request.form.getlist('platforms')
    # 在此处添加你希望的处理逻辑
    try:
        executeData(files['commission_file'], files['search_file'], platforms)
    except Exception as e:
        return render_template('error.html', err=e)
    
    return redirect(url_for('download_page', filename=os.path.basename(files['commission_file'])))

@app.route('/download/<filename>')
def download_page(filename):
    return render_template('download.html', filename=filename)

@app.route('/download_file/<filename>')
def download_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename, as_attachment=True)

if __name__ == '__main__':
    app.run(debug=True)